package com.bn.commerce.gifts;

import java.io.IOException;

import javax.servlet.ServletException;

import atg.commerce.CommerceException;
import atg.commerce.gifts.GiftlistManager;
import atg.commerce.gifts.GiftlistTools;
import atg.commerce.gifts.InvalidGiftQuantityException;
import atg.commerce.order.CommerceItem;
import atg.commerce.order.CommerceItemNotFoundException;
import atg.commerce.order.InvalidParameterException;
import atg.commerce.order.ShippingGroup;
import atg.core.util.ResourceUtils;
import atg.droplet.DropletException;
import atg.droplet.DropletFormException;
import atg.projects.store.gifts.StoreGiftlistFormHandler;
import atg.projects.store.profile.StoreProfileTools;
import atg.repository.Repository;
import atg.repository.RepositoryException;
import atg.repository.RepositoryItem;
import atg.servlet.DynamoHttpServletRequest;
import atg.servlet.DynamoHttpServletResponse;


public class BNGiftListFormHandler extends StoreGiftlistFormHandler{

	private GiftlistTools giftlistTools = null;
	private  RepositoryItem profileRepository;
	private String giftlistItems;
	private ShippingGroup mShippingGroup;
	private String moveItemFromGiftlistSuccessURL;
	private String moveItemFromGiftlistErrorURL;

	@Override
	public boolean handleAddItemToGiftlist(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException, CommerceException {
		try
		{
			checkGiftlistAccess();

			if (!(checkFormRedirect(null, getAddItemToGiftlistErrorURL(), pRequest, pResponse)))
				return false;
			preAddItemToGiftlist(pRequest, pResponse);

			if (validateGiftlistId(pRequest, pResponse))
			{
				if (!(checkFormRedirect(null, getAddItemToGiftlistErrorURL(), pRequest, pResponse)))
					return false;
				addItemToGiftlist(pRequest, pResponse);

				if (!(checkFormRedirect(null, getAddItemToGiftlistErrorURL(), pRequest, pResponse))) {
					return false;
				}
				postAddItemToGiftlist(pRequest, pResponse);
			}
		}
		catch (InvalidGiftQuantityException exc)
		{
			processException(exc, "quantityLessThanOrEqualToZero", pRequest, pResponse);
		}
		catch (CommerceException oce) {
			processException(oce, "errorAddingToGiftlist", pRequest, pResponse);
		}
		return checkFormRedirect(getAddItemToGiftlistSuccessURL(), getAddItemToGiftlistErrorURL(), pRequest, pResponse);
	}

	public boolean handleMoveItemFromGiftlist(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException, CommerceException {
		try
		{
			GiftlistManager mgr = getGiftlistManager();
			mgr.buyItemFromGiftlist((String)getGiftlistId(), (String)getGiftlistItems(), getOrder(), getShippingGroup());
		}
		catch (Exception oce) {
			processException(oce, "errorAddingToGiftlist", pRequest, pResponse);
		}
		return checkFormRedirect(getMoveItemFromGiftlistSuccessURL(), getMoveItemFromGiftlistErrorURL(), pRequest, pResponse);
	}


	protected void checkGiftlistAccess()
			throws CommerceException{
		if ((isEnableSecurity()) && (!(isGiftlistOwner(getGiftlistId(), getProfile().getRepositoryId()))))
			throw new CommerceException("No Access");
	}

	protected boolean isGiftlistOwner(String pGiftlistId, String pProfileId){
		if ((pGiftlistId == null) || (pProfileId == null)) {
			return false;
		}
		String owner = getGiftlistOwner(pGiftlistId);
		String wishlistId = getWishlistId(pProfileId);
		if ((owner != null) && (!(owner.equalsIgnoreCase(pProfileId)))) {
			return false;
		}
		return ((owner != null) || ((wishlistId != null) && (wishlistId.equalsIgnoreCase(pGiftlistId))));
	}

	public String getGiftlistOwner(String pGiftlistId)
	{
		if (isLoggingDebug())
			logDebug("Inside getGiftlistOwner: " + pGiftlistId);
		GiftlistTools tools = getGiftlistTools();
		try {
			Repository rep = tools.getGiftlistRepository();
			RepositoryItem giftlist = rep.getItem(pGiftlistId, tools.getGiftlistItemDescriptor());

			if (giftlist != null) {
				RepositoryItem owner = (RepositoryItem)giftlist.getPropertyValue(tools.getOwnerProperty());
				if (owner != null)
					return ((String)owner.getPropertyValue("id"));
			}
			else {
				return null;
			}
		} catch (RepositoryException r) {
			if (isLoggingError())
				logError(r);
			return null;
		}
		return null;
	}

	public String getWishlistId(String pProfileId)
	{
		if (isLoggingDebug())
			logDebug("Inside getWishlistId: " + pProfileId);
		GiftlistTools tools = getGiftlistTools();
		RepositoryItem profile = tools.getProfile(pProfileId);
		RepositoryItem wishlist = (RepositoryItem)profile.getPropertyValue(tools.getWishlistProperty());
		if (wishlist != null) {
			return ((String)wishlist.getPropertyValue("id"));
		}
		return null;
	}

	public GiftlistTools getGiftlistTools() {
		return giftlistTools;
	}

	public void setGiftlistTools(GiftlistTools giftlistTools) {
		this.giftlistTools = giftlistTools;
	}

	public void preAddItemToGiftlist(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse)
			throws ServletException, IOException
			{
		if (getQuantity() <= 0L)
		{
			String msg = formatUserMessage("quantityLessThanOrEqualToZero", pRequest, pResponse);
			addFormException(new DropletFormException(msg, "errorAddingToGiftlist"));

		}

		if ((getCatalogRefIds() == null) || (getCatalogRefIds().length == 0) || (getCatalogRefIds()[0] == null))

		{
			addFormException(new DropletException(formatUserMessage("noItemsToAdd", pRequest, pResponse)));
		}
		StoreProfileTools profileTools = (StoreProfileTools)getProfileTools();

		if (!(profileTools.isUserLoggedIn(getProfile())))

		{
			String notLoggedIn = formatUserMessage("giftlistNotLoggedIn", pRequest, pResponse);
			addFormException(new DropletException(notLoggedIn, notLoggedIn));
			setAddItemToGiftlistErrorURL(getAddItemToGiftlistLoginURL());


			addLoginErrorParameter(pRequest, pResponse);

			try
			{
				saveDataIntoSession(getAddItemToGiftlistSuccessURL());
			}
			catch (CommerceItemNotFoundException ex) {
				processException(ex, "errorAddingToGiftlist", pRequest, pResponse);
			}
			catch (InvalidParameterException ex) {
				processException(ex, "errorAddingToGiftlist", pRequest, pResponse);
			}

			return;
		}

		super.preAddItemToGiftlist(pRequest, pResponse);
			}

	private void saveDataIntoSession(String pRedirectURL)
			throws ServletException, CommerceItemNotFoundException, InvalidParameterException
			{
		if ((getItemIds() != null) && (getItemIds().length > 0))

		{
			String commerceItemId = getItemIds()[0];
			CommerceItem item = getOrder().getCommerceItem(commerceItemId);
			if (item != null) {
				getSessionBean().getValues().put("commerceItemId", commerceItemId);

				getSessionBean().getValues().put("skuIdToAdd", item.getCatalogRefId());

				getSessionBean().getValues().put("productIdToAdd", item.getAuxiliaryData().getProductId());
				getSessionBean().getValues().put("siteId", item.getAuxiliaryData().getSiteId());
			}
		}
		else
		{
			getSessionBean().getValues().put("skuIdToAdd", getCatalogRefIds()[0]);
			getSessionBean().getValues().put("productIdToAdd", getProductId());
		}
		getSessionBean().getValues().put("giftListIdToAdd", (getProfile().isTransient()) ? null : getGiftlistId());

		getSessionBean().getValues().put("quantityToAdd", Long.valueOf(getQuantity()));

		getSessionBean().getValues().put("redirectAfterSuccessLoginURL", pRedirectURL);
			}

	public RepositoryItem getProfileRepository() {
		return profileRepository;
	}

	public void setProfileRepository(RepositoryItem profileRepository) {
		this.profileRepository = profileRepository;
	}

	public ShippingGroup getShippingGroup() {
		if (this.mShippingGroup == null) {
			this.mShippingGroup = ((ShippingGroup)getOrder().getShippingGroups().get(0));
		}
		return this.mShippingGroup;
	}

	public void setShippingGroup(ShippingGroup mShippingGroup) {
		this.mShippingGroup = mShippingGroup;
	}

	public String getMoveItemFromGiftlistSuccessURL() {
		return moveItemFromGiftlistSuccessURL;
	}

	public void setMoveItemFromGiftlistSuccessURL(
			String moveItemFromGiftlistSuccessURL) {
		this.moveItemFromGiftlistSuccessURL = moveItemFromGiftlistSuccessURL;
	}

	public String getMoveItemFromGiftlistErrorURL() {
		return moveItemFromGiftlistErrorURL;
	}

	public void setMoveItemFromGiftlistErrorURL(String moveItemFromGiftlistErrorURL) {
		this.moveItemFromGiftlistErrorURL = moveItemFromGiftlistErrorURL;
	}

	public String getGiftlistItems() {
		return giftlistItems;
	}

	public void setGiftlistItems(String giftlistItems) {
		this.giftlistItems = giftlistItems;
	}
}
